<?php

/* ----------------------------------------------
  Caloris: Administration Store Extensions

  $Id$
  $Author$

  List of downloadable extensions
  ---------------------------------------------- */

require_once("../../../index.php");
Caloris\ACL::authenticate();

define('_MODULE_ACTIVE', 'store');

$urlExtensions = _CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/extensions.xml';

if ($_REQUEST["function_name"] == 'store_extension_install') {

    if (Caloris\ACL::authorize("extensions") == 1) {
        $file_path = _CALSET_PATHS_BASE . _CALSET_DIRS_EXTENSION . '/' . $_POST["file"] . '.php';

        if (!file_exists($file_path)) {
            $ch = curl_init(); // create cURL handle (ch)
            if (!$ch) {
                die("Couldn't initialize");
            }

            $ret = curl_setopt($ch, CURLOPT_URL, 'http://caloris.cz/store/extensions/' . $_POST["file"] . '.txt');
            $ret = curl_setopt($ch, CURLOPT_HEADER, false);
            $ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $ret = curl_setopt($ch, CURLOPT_NOBODY, 0);
            $ret = curl_setopt($ch, CURLOPT_TIMEOUT, 40);
            $ret = curl_exec($ch);

            if (empty($ret)) {
                die(curl_error($ch));
                curl_close($ch);
            } else {
                $info = curl_getinfo($ch);
                curl_close($ch);

                if (empty($info['http_code'])) {
                    die("No HTTP code was returned");
                } else {
                    if (strcmp(md5($ret), $_POST["checksum"]) == 0) {
                        $file = fopen($file_path, 'w', 1);
                        fwrite($file, $ret);
                        fclose($file);
                    } else {
                        header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/addons.extensions.store.php?msg=" . urlencode("Soubory nemají stejný obsah. Instalace zrušena: " . md5($ret) . '-' . $_POST["checksum"]));
                        exit();
                    }
                }
            }

            if ($_POST["j"] != 1) {
                header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/addons.extensions.store.php");
                exit();
            } else {
                echo "{\"msg\": \"done\"}";
                exit();
            }
        }
    } else {
        header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/store.extensions.php?msg=" . urlencode("Nemáte oprávnění"));
        exit();
    }
}


// Registering new extensions

$extensionDirectory = scandir(_CALSET_PATHS_BASE . _CALSET_DIRS_EXTENSION);

for ($a = 0; $a < count($extensionDirectory); $a++) {
    $extensionNameNoExt = substr($extensionDirectory[$a], 0, -4);
    $extensionFileName = $extensionDirectory[$a];

    if ($extensionDirectory[$a] == '.' or $extensionDirectory[$a] == '..') {
        
    } else {
        // Search for existence of extensions in extensions directory. Deletes records in XML file for non-existing extensions, adds XML descriptions for extension files
        $xmlExtensionsCheck = new Caloris\XML();
        $xmlExtensionsCheck->source($urlExtensions);
        $xmlExtensionsCheck->filter('//extension[@id="' . $extensionNameNoExt . '"]');


        if (count($xmlExtensionsCheck->output) == 0) {

            $filein = Caloris\IO::get(_CALSET_PATHS_BASE . _CALSET_DIRS_EXTENSION . '/' . $extensionFileName);
            $startin = strpos($filein, "/*");
            $endin = strpos($filein, "*/");
            $descriptor = explode(":", substr($filein, ($startin + 2), (($endin - $startin)) - 2));

            // Find the comment section of the extension
            $extensionPositionStart .= strpos($filein, '<extension');
            $extensionPositionEnd .= strpos($filein, '</extension>') + 12;
            $extensionXmlString = html_entity_decode(substr($filein, $extensionPositionStart, ($extensionPositionEnd - $extensionPositionStart)), 0, 'UTF-8');
            $extensionXml = simplexml_load_string($extensionXmlString);

            if (count($extensionXml)) {
                $extensionName = $extensionXml[0]["id"];
                $extensionAuthor = $extensionXml[0]->author;
                $extensionDescription = $extensionXml[0]->description;
                $extensionModule = $extensionXml[0]->modules->name;
            } else {
                $extensionName = $extensionFileName;
                $extensionAuthor = '';
                $extensionDescription = $descriptor[1];
                $extensionModule = '';
            }

            $extension = simplexml_load_file($urlExtensions);
            $extensionExists = $extension->xpath('//extension[@id="' . $extensionNameNoExt . '"]');

            $xt = $extension->AddChild("extension");
            $xt["id"] = $extensionName;
            $xt->author = $extensionAuthor;
            $xt->description = $extensionDescription;

            if (count($extensionModule) > 0) {
                $md = $xt->AddChild("modules");

                for ($c = 0; $c < count($extensionModule); $c++) {
                    $md->name[] = $extensionModule[$c];
                }
            }

            $extension->asXML($urlExtensions);
        }
    }

    unset($extensionNameNoExt);
}

$content = '
<p class="perex" style="color: red;" id="msg">[cal:predefs(msg) /]</p>

<h1>Store: Extenze</h1>
<p style="padding-bottom: 20px;">Extenze jsou funkce rozšiřující možnosti stránek. Zapisují se obvykle takto &#91;cal:jmenoextenze /&#93;, pokud mají argumenty, pak například takto &#91;cal:jménoextenze(první;druhý) /&#93;. Systémové extenze by neměly být mazány. Při jejich vymazání může dojít ke snížené funkčnosti stránek.</p>

<h2>Seznam extenzí</h2>
';

$ch = curl_init();

if (!$ch) {
    die("Couldn't initialize");
}

$ret = curl_setopt($ch, CURLOPT_URL, "http://caloris.cz/store/caloris_extensions.xml");
$ret = curl_setopt($ch, CURLOPT_HEADER, false);
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ret = curl_setopt($ch, CURLOPT_NOBODY, 0);
$ret = curl_setopt($ch, CURLOPT_TIMEOUT, 40);

// execute
$ret = curl_exec($ch);

if (empty($ret)) {
    die(curl_error($ch));
    curl_close($ch); // close cURL handler
} else {
    $info = curl_getinfo($ch);
    curl_close($ch); // close cURL handler

    if (empty($info['http_code'])) {
        die("No HTTP code was returned");
    } else {
        $xma = simplexml_load_string($ret);
    }
}

$xmr = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/settings.xml');

if (count($xma->extensions->children()) > 0) {
    $content .= '
<table class="table table-striped">
    <tr>
        <th>Název extenze</th>
        <th>Popis</th>
        <th style="width: 20px;"></th>
        <th style="width: 80px;"></th>
    </tr>
';
    foreach ($xma->extensions->children() as $child) {
        // Smazání extenze, u které není soubor
        $gname = $child->getName();

        if (!file_exists(_CALSET_PATHS_BASE . _CALSET_DIRS_EXTENSION . '/' . $xma->extensions->{$gname}->name . '.php')) {
            $system = '
<form action="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/store/addons.extensions.store.php" method="post">
<input type="hidden" name="function_name" value="store_extension_install" />
<input type="hidden" name="transport_type" value="form" />
<input type="hidden" name="checksum" value="' . $xma->extensions->{$gname}->checksum . '" />
<input type="hidden" name="file" value="' . $xma->extensions->{$gname}->name . '" />
<input type="submit" value="Nainstalovat" class="btn btn-success" />
</form>';
        } else {
            $system = 'Nainstalováno';
        }

        $content .= '
	<tr id="trbl_' . $gname . '" >
		<td><a href="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/store/addons.extensions.store.editor.php?file=' . $xma->extensions->{$gname}->name . '&checksum=' . $xma->extensions->{$gname}->checksum . '">' . $xma->extensions->{$gname}->name . '</a></td>
		<td>' . $xma->extensions->{$gname}->description . '</td>
		<td><a href="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/store/addons.extensions.store.editor.php?file=' . $xma->extensions->{$gname}->name . '&checksum=' . $xma->extensions->{$gname}->checksum . '"><img src="' . _CALSET_PATHS_URI . _CALSET_DIRS_ADMIN_IMAGE . '/images/edit.gif" alt="Upravit" width="16" height="16" /></a>
		</td>
		<td>' . $system . '</td>
	</tr>';
    }

    $content .= '</table>';
} else {
    $content .= '<p>Žádné extenze nenalezeny</p>';
}

$data["title"] = 'Store: Extenze';

$tmpl = new Caloris\Template;
$tmpl->input($content);
$tmpl->renderHead($data);
echo $tmpl->renderBody('caloris-admin');